#!/bin/bash

script_path=$(dirname "$0")
model_name=$1
# echo $script_path
# echo $model_name

shift
input_array=("$@")

for element in "${input_array[@]}"; do
    echo "Processing requestrate element: $element"
done

echo $model
echo $in
echo $out
# 定义需要执行的脚本所在的路径
SCRIPTS_DIR="$script_path/test_case/$model_name"  # 将此路径替换为你的脚本所在的路径

CONF_DIR="$script_path/conf_case/$model_name"
rm "$CONF_DIR"/*
# 定义存储 benchmark 表格的文件路径
OUTPUT_FILE="$script_path/benchmark/${type}/benchmark_results_${model_name}_input${in}_output${out}_$(date +%Y%m%d%H%M%S).txt" # 添加时间戳到文件名
echo $OUTPUT_FILE
# echo $OUTPUT_FILE

# echo $SCRIPTS_DIR
req_count=0
for conf in "$CONF_DIR"/*.json
do
  cp "$conf" ../../conf/config.json
  
  echo "Config file '$conf' copied to conf"
  
  echo "Launching Daemon ... "
  bash $script_path/start_daemon.sh
  
  sleep 5
  
  # 循环执行路径下的所有 .sh 脚本
    for script in "$SCRIPTS_DIR"/*.sh
    do
      echo "Time $req_count"
      echo "Running script: $script, Request Rate ${input_array[$req_count]}"
      script -q -c "bash $script ${input_array[$req_count]} $conf $in $out" /dev/null | tee $script_path/script_output.txt
      # 检查脚本是否成功执行
      # if [ $? -ne 0 ]; then
      # 	echo "Error: Script $script failed to execute."
      # 	exit 1
      # fi
      echo $conf
      #  提取从关键字到文件末尾的所有行，并在前面加上脚本名称和时间戳
      timestamp=$(date +%Y-%m-%d_%H:%M:%S) 
      maxPrefillBatchSize=$(jq -r '.BackendConfig.ScheduleConfig.maxPrefillBatchSize' "$conf")
      maxBatchSize=$(jq -r '.BackendConfig.ScheduleConfig.maxBatchSize' "$conf")
      prefillTimeMsPerReq=$(jq -r '.BackendConfig.ScheduleConfig.prefillTimeMsPerReq' "$conf")

      echo "## We are doing $conf ... " >> "$OUTPUT_FILE"
      echo "## Parameters are: maxPrefillBatchSize $maxPrefillBatchSize, maxBatchSize $maxBatchSize, prefillTimeMsPerReq $prefillTimeMsPerReq, RequestRate ${input_array[$req_count]}" >> "$OUTPUT_FILE"
      echo "## Results from $script (Timestamp: $timestamp):" >> "$OUTPUT_FILE"
      
      awk '/The BenchMark test performance metric result is:/{p=1};p' $script_path/script_output.txt >> "$OUTPUT_FILE"
    done
    ((req_count++))
    
    
    echo "Benchmark results saved to $OUTPUT_FILE"
  
  echo "Job finished, closing Daemon"
  bash $script_path/kill_daemon.sh
  
  sleep 10 
done

rm "$CONF_DIR"/*

exit